//
//  PartyNoticeViewController.m
//  UESTCPioneer
//
//  Created by Sway on 14-3-5.
//  Copyright (c) 2014年 Sway. All rights reserved.
//

#import "PartyNoticeViewController.h"
#import "UPTableView.h"
#import "UPTitleCell.h"
#import "UPMainInfoCell.h"
#import "UPFooterCell.h"
#import "LeveyTabBarController.h"
#import "shareEditView.h"

@interface PartyNoticeViewController ()<UPFooterCellDelegate,UPTitleCellDelegate>
{
    BOOL _isManager;
    NSDictionary *_observerEntity ;
}

@end

@implementation PartyNoticeViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self hideTopView];
    tableViewTopConstraint.constant = 0;
    UnreadKey=kUnreadPartyNoticeKey;
    
    //    [self.view addSubview:label];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    /*修改*/
    [dropbtn setTitle:@"全部" forState:UIControlStateNormal];
    /**/

    requestData=@{@"type":@"getNoticeOrAnnounce"
                  ,@"userId":[constant getUserId]
                  ,@"userName":[constant getUserName]
                  ,@"page":@"1"
                  ,@"typepid":@"1"
                  ,@"level":@"3"};
    /**/
    entityName=kPartyNoticeNewsEntityName;
    entityMapping=[Mapping PartyNoticeMapping];

    commentIdKey=@"noticeid";
    commentListRequestData=@{@"type":@"getNAcomment"
                             ,@"noticeid":@"0"
                             ,@"userId":[constant getUserId]
                             ,@"typepid":@"1"
                             ,@"page":@"1"};
    

    commentWriteIdKey=@"gonggaoid";
    commentWriteRequestData=@{@"type":@"writeNAcomment"
                              ,@"fromusername":[constant getUserName]
                              ,@"fromuserid":[constant getUserId]
                              ,@"gonggaoid":@"0"
                              ,@"content":@""
                              ,@"typepid":@"1"};
    commentContentKey=@"content";
    commentListKeyMapping=@{@"commentContent":@"commentBody",@"commentAuthor":@"userName",@"commentDate":@"commentDate"};
    
    //界面显示，监听通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationCancelCollectrefresh:) name:kNotificationCancelCollect object:_observerEntity];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.leveyTabBarController.navigationItem setTitle:@"通知公告"];
    /*修改*/
    self.isPartyNotice = YES;
    [self judgeIsManager];
    /**/
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(ScreenTouch)];
    [self.tableView addGestureRecognizer:tapGesture];
    
    //清空icon 的角标
    //当应用是在有remote通知时是通过点击icon而不是点击通知进入时
    //   1.用户进入应用后没有进入“通知公告”页面，者isEnterFromRemote = NO；也就是说用户没有读新的通知，因此icon的角标保留
    //   2.用户进入应用后点击进入了“通知公告”页面，此时不管他是不是真的看过新的通知，都认为他已经读了新消息，然后在通知页面将isEnterFromRemote设置为YES，因此去掉icon角标
    if (![Unread getIsEnterFromRemote]) {
        [Unread setIsEnterFromRemote:YES];
    }
    
//    /*添加20141026*/
//    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(235, 0, 110, 44)];
//    [btn setTitleEdgeInsets:UIEdgeInsetsMake(8, 0, 8, 25)];
//    [btn.titleLabel setTextAlignment:NSTextAlignmentLeft];
//    NSString *title = @"全部";
//    
//    if ([constant getCurrentView] == 2) {
//        title = @"最新";
//    }
//    
//    [btn setTitle:title forState:UIControlStateNormal];
//    btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
//    [btn.titleLabel setFont:[UIFont systemFontOfSize:13.0f]];
//    btn.tintColor = [UIColor whiteColor];
//    [btn addTarget:self action:@selector(dropClicked:) forControlEvents:UIControlEventTouchUpInside];
//    
//    UIImageView *xiala = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"xiala.png"]];
//    xiala.contentMode = UIViewContentModeScaleAspectFit;
//    xiala.frame = CGRectMake(88, 8+9, 12, 12);
//    xiala.tag = 22;
//    [btn addSubview:xiala];
//    
//    dropbtn = btn;
//    UIBarButtonItem *barItem2=[helper BarButtonItemWithUIButton:btn ButtonOrigin:CGPointMake(0, 0) CustomViewSize:CGSizeMake(110, 44)];
//    
//    self.leveyTabBarController.navigationItem.rightBarButtonItem = barItem2;
//    /**/
    [self _initBarButton];
}
#pragma  mark  触摸事件
-(BOOL)ScreenTouch{
    
    if(dropDown == nil) {
        return NO;
    } else {
        [dropDown hideDropDown:dropbtn];
        [self rel];
        return YES;
    }
}

/*修改*/
-(void)judgeIsManager{
    //@判断是否为管理员
    NSString *userId=[constant getUserId];
    NSString *lastChar =[userId substringFromIndex:[userId length]-1];
    if ([lastChar isEqualToString:@"1"] || [lastChar isEqualToString:@"2"]){
        //管理员
        _isManager = YES;
    }else{
        _isManager = NO;
    }
}
/**/
- (void)dropClicked:(id)sender {
    NSArray * arr = [[NSArray alloc] init];
    arr = [NSArray arrayWithObjects:@"全部",@"校级",@"院级",@"支部",nil];
    if(dropDown == nil) {
        CGFloat newHeight = 180;
        CGRect newfram = CGRectMake(215, -80, 105, 80);
        dropDown = [[NIDropDown alloc] initDropDown:sender withFram:newfram withHeight:newHeight content:arr forView:self.view];
        dropDown.delegate = self;
    }
    else {
        [dropDown hideDropDown:sender];
        [self rel];
    }
}

-(void)niDropDownDelegateMethod:(NIDropDown *)sender ForTitle:(NSString *)title ForIndex:(NSInteger)index{
    if ([title isEqualToString:@"校级"]){
        requestData=[RequestData NoticeDataWithLevel:0];
        [self.tableView beginRefreshing];
    }
    else if ([title isEqualToString:@"院级"]){
        requestData=[RequestData NoticeDataWithLevel:1];
        [self.tableView beginRefreshing];
    }
    else if ([title isEqualToString:@"支部"]){
        requestData=[RequestData NoticeDataWithLevel:2];
        [self.tableView beginRefreshing];
    }
    else if ([title isEqualToString:@"全部"]){
        requestData=[RequestData NoticeDataWithLevel:3];
        [self.tableView beginRefreshing];
    }
    [self rel];
}

//每个分区的行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 3;
}

//表的分区数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return [tableViewEntitiesArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell=[super tableView:tableView cellForRowAtIndexPath:indexPath];
    
    PartyNoticeNewsEntity *entity = tableViewEntitiesArray[indexPath.section];
    //    NSLog(@"entity = %@",entity);
    
    if (indexPath.row == 0) {
        
        UPTitleCell *titleCell = (UPTitleCell*)cell;
        
        [titleCell setTitle:entity.comfrom];
        /**/
        titleCell.delegate=self;
        [titleCell setCollectButtonEnable:YES];
        
        
        //收藏按钮
        BOOL collected = [entity.shoucang boolValue];
        if (collected)[titleCell setCollectButtonStatus:YES];
        else [titleCell setCollectButtonStatus:NO];
        return cell;
    }
    else if (indexPath.row == 1) {
        UPMainInfoCell*cell2=(UPMainInfoCell*)cell;
        return cell2;
    }
    else {
        UPFooterCell*cell3=(UPFooterCell*)cell;
        cell3.delegate=self;
        
        //标记已读按钮
        [cell3 setMarkButtonEnable:YES];
        [cell3 setMarkButtonStatus:[entity.chakan boolValue]];
        [cell3.markButton setImage:[UIImage imageNamed:@"read"] forState:UIControlStateNormal];
        [cell3.markButton setImage:[UIImage imageNamed:@"read_mark"] forState:UIControlStateSelected];
        
        
        /*修改*/
        if (_isManager) {
            [cell3 setShareButtonEnable:YES];
            [cell3 setShareNum:[entity.transnum integerValue]];
        }
        /*修改*/
        
        UIButton *btn1 = (UIButton *)[cell3.contentView viewWithTag:btn1Tag];
        //        UIButton *btn2 = (UIButton *)[cell3.contentView viewWithTag:btn2Tag];
        
        btn1.hidden = NO;
        //        btn2.hidden = NO;
        
        return cell3;
    }
    
}




//修改行高度的位置
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return [super tableView:tableView heightForRowAtIndexPath:indexPath];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 5;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    // indexPath.section,根据分组进行更精确的配置
    return 5;
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - UPFooterCellDelegate

-(void)shareButtonClick:(NSInteger)theId{
    shareEditView *shareView = [[shareEditView alloc]init];
    
    PartyNoticeNewsEntity *entity=[PublicMethod entity:kPartyNoticeNewsEntityName WithId:theId];
    
    [shareView popUpCommentViewWithShareSourceInfo:entity.newsBody CommitBlock:^(NSString *commentBody) {
        /*
         type=transmitNotice&naid=13&userId=0012005130022&userName=xiaopangzi&content=13&type
         
         //注意，转发只有管理员可以，管理员id末位为1或者2
         */
        
        
        //@评论内容要加上@对方用户的信息
        commentBody=[commentBody stringByAppendingString:[NSString stringWithFormat:@"@%@//",entity.comfrom]];
        //        commentBody = [commentBody  stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        //@判断是否为管理员
        NSString *userId=[constant getUserId];
        
        NSDictionary *ShareRequestData = @{@"type":@"transmitNotice"
                                           ,@"naid":[NSString stringWithFormat:@"%d",theId]
                                           ,@"content":commentBody
                                           ,@"userId":userId
                                           ,@"userName":[constant getUserName]
                                           ,@"typepid":@"1"
                                           };
        
        
        
        [NetworkCenter AFRequestPartyNoticeWithData:ShareRequestData SuccessBlock:^(AFHTTPRequestOperation *operation, id resultObject) {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:resultObject options:NSJSONReadingMutableLeaves error:nil];
            if ([dic[@"result"] isEqualToString:@"success"]){
                [Alert showAlert:@"转发成功"];
                [shareView closeCommentView];
                [self.tableView beginRefreshing];
                return ;
            }
            else {
                [Alert showAlert:@"转发失败"];
                return;
            }
        } FailureBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
            [Alert showAlert:@"转发错误"];
            return ;
        }];
        
        
    }];
    
}


/*修改*/


-(void)shareButtonClick1:(NSInteger)theId{
    shareEditView *shareView = [[shareEditView alloc]init];
    
    PartyNoticeNewsEntity *entity = [PublicMethod entity:kPartyNoticeNewsEntityName WithId:theId];
    
    [shareView popUpCommentViewWithShareSourceInfo:entity.newsBody CommitBlock:^(NSString *commentBody) {
        //@评论内容要加上@对方用户的信息
        commentBody=[commentBody stringByAppendingString:[NSString stringWithFormat:@"@%@//",entity.userName]];
        
        //@判断是否为管理员
        NSString *userId=[constant getUserId];
        /*修改*/
        
        NSDictionary *ShareRequestData = @{@"type":@"transmitNotice"
                                           ,@"naid":[NSString stringWithFormat:@"%d",theId]
                                           ,@"content":commentBody
                                           ,@"userId":userId
                                           ,@"userName":[constant getUserName]
                                           ,@"typepid":@"1"
                                           };
        
        
        
        [NetworkCenter requestPartyNotice:ShareRequestData ImageArray:nil SuccessBlock:^(id resultObject) {
            NSDictionary *dic= [NSJSONSerialization JSONObjectWithData:resultObject options:NSJSONReadingMutableLeaves error:Nil];
            if ([dic[@"result"] isEqualToString:@"success"]){
                [Alert showAlert:@"转发成功"];
                [self.navigationController popViewControllerAnimated:YES];
            }
            else {
                [Alert showAlert:@"转发失败"];
            }
        } failure:^(NSError *error) {
            [Alert showAlert:@"转发错误"];
        }];
        
    }];
}
/**/



#pragma mark - UPTitleCell Delegate
/*
 type=naViewcollect&view_collect=0&shoucang=1&fromusername=xiaopangzi&fromuserid=00120
 
 */

-(void)UPTitleCell:(UPTitleCell *)cell CollectButtonClick:(UIButton *)button{
    
    if (cell.collecting){
        [Alert showAlert:@"点太快了"];
        return;
    }
    NSInteger flag = button.selected;
    NSDictionary *CollectReqeustData = @{
                                         @"type":@"naViewcollect"
                                         ,@"view_collect":@"0"
                                         ,@"shoucang":[NSString stringWithFormat:@"%d",flag]
                                         ,@"fromusername":[constant getUserName]
                                         ,@"fromuserid":[constant getUserId]
                                         ,@"gonggaoid":[NSString stringWithFormat:@"%d",cell.theId]
                                         ,@"typepid":@"1"
                                         };
    
    //异步锁
    cell.collecting=YES;
    [NetworkCenter AFRequestWithData:CollectReqeustData SuccessBlock:^(AFHTTPRequestOperation *operation, id resultObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:resultObject options:NSJSONReadingMutableLeaves error:Nil];
        if ([dic[@"result"] isEqualToString:@"success"]){
            if (flag==1) {
                [Alert showAlert:@"已收藏！"];
                /*修改*/
                PartyNoticeNewsEntity *entity = tableViewEntitiesArray[cell.indexPath.section];
                entity.shoucang = @1;
                /**/
            }else{
                [Alert showAlert:@"已取消！"];
                /*修改*/
                PartyNoticeNewsEntity *entity = tableViewEntitiesArray[cell.indexPath.section];
                entity.shoucang = @0;
                /**/
            }
        }
        else {
            /*修改*/
            PartyNoticeNewsEntity *entity = tableViewEntitiesArray[cell.indexPath.section];
            NSNumber *oldShouCang =  entity.shoucang ;
            [Alert showAlert:@"失败!"];
            entity.shoucang = oldShouCang;
            /**/
        }
        cell.collecting=NO;
    } FailureBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
        [Alert showAlert:@"发生错误"];
        cell.collecting=NO;
    }];
    
}

-(void)UPFooterCell:(UPFooterCell *)cell markButtonClick:(UIButton *)button{
    
    if (cell.marking){
        [Alert showAlert:@"点太快了"];
        return;
    }
    
    BOOL flag = button.selected;
    cell.marking=YES;
    NSDictionary *MarkReqeustData = @{
                                      @"type":@"naViewcollect"
                                      ,@"view_collect":@"1"
                                      ,@"shoucang":[NSString stringWithFormat:@"%d",flag]
                                      ,@"fromusername":[constant getUserName]
                                      ,@"fromuserid":[constant getUserId]
                                      ,@"gonggaoid":[NSString stringWithFormat:@"%d",cell.theId]
                                      ,@"typepid":@"1"
                                      };
    
    [NetworkCenter AFRequestWithData:MarkReqeustData SuccessBlock:^(AFHTTPRequestOperation *operation, id resultObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:resultObject options:NSJSONReadingMutableLeaves error:Nil];
        if ([dic[@"result"] isEqualToString:@"success"]){
            //            [Alert showAlert:@"标记成功！"];
            
        }else {
            //            [Alert showAlert:@"标记失败!"];
            [cell.markButton setImage:[UIImage imageNamed:@"read_mark"] forState:UIControlStateNormal];
            [cell.markButton setImage:[UIImage imageNamed:@"read_mark"] forState:UIControlStateSelected];
        }
        
        cell.marking=NO;
    } FailureBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
        [Alert showAlert:@"发生错误"];
        cell.marking=NO;
    }];
}

-(void)notificationCancelCollectrefresh:(NSNotification*)notify{
    
    NSDictionary * dict = notify.object;
    for (int i = 0; i < tableViewEntitiesArray.count; i++) {
        PartyNoticeNewsEntity *entity = tableViewEntitiesArray[i];
        NSString *theid = [NSString stringWithFormat:@"%@",entity.theId];
        if ([dict[@"id"] isEqualToString:theid]) {
            entity.shoucang = @0;
            break;
        }
    }
    [self.tableView reloadData];
}

//-(void)WholeNewsButtonClick:(NSInteger)theId{
//    BOOL result = [self ScreenTouch];
//    if (result) {
//        return;
//    }
//    
//    PartyNoticeNewsEntity *entity = [PublicMethod entity:kPartyNoticeNewsEntityName WithId:theId];
//    
//    NSString *content =entity.newsBody;
//    UIViewController *viewController = [[UIViewController alloc]init];
//    
//    [viewController.view setFrame:self.view.frame];
//    [viewController.view setBackgroundColor:[UIColor colorWithRed:232.0f/255.0f green:232.0f/255.0f blue:232.0f/255.0f alpha:1.0f]];
//    UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(viewController.view.frame.origin.x, viewController.view.frame.origin.y, viewController.view.frame.size.width, 45)];
//    
//    NSString *title = entity.comfrom;
//    label.text = title;
//    [label setBackgroundColor:[UIColor colorWithRed:232.0f/255.0f green:232.0f/255.0f blue:232.0f/255.0f alpha:1.0f]];
//    [label setFont:[UIFont systemFontOfSize:17]];
//    //    [label setTextColor:[UIColor grayColor]];
//    //文字居中显示
//    label.textAlignment = NSTextAlignmentCenter;
//    //自动折行设置
//    //    label.lineBreakMode = NSLineBreakByWordWrapping;
//    label.numberOfLines = 0;
//    label.adjustsFontSizeToFitWidth = YES;
//    
//    [viewController.view addSubview:label];
//    [label setTranslatesAutoresizingMaskIntoConstraints:NO];
//    [viewController.view addConstraint:[NSLayoutConstraint constraintWithItem:label
//                                                                    attribute:NSLayoutAttributeTop
//                                                                    relatedBy:NSLayoutRelationEqual
//                                                                       toItem:viewController.view
//                                                                    attribute:NSLayoutAttributeTop
//                                                                   multiplier:1 constant:0]];
//    
//    [viewController.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-3.0-[label]-3.0-|" options:0 metrics:Nil views:NSDictionaryOfVariableBindings(label)]];
//    [viewController.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[label(==45)]" options:0 metrics:Nil views:NSDictionaryOfVariableBindings(label)]];
//    
//    //    NSLog(@"执行了label = %@",label);
//    UITextView *textView = [[UITextView alloc]init];
//    //    [textView setTextColor:[UIColor grayColor]];
//    [textView setText:content];
//    [textView setEditable:NO];
//    [textView setScrollEnabled:YES];
//    [textView setBackgroundColor:[UIColor colorWithRed:232.0f/255.0f green:232.0f/255.0f blue:232.0f/255.0f alpha:1.0f]];
//    [textView setFont:[UIFont systemFontOfSize:18]];
//    [viewController.view addSubview:textView];
//    [textView setTranslatesAutoresizingMaskIntoConstraints:NO];
//    [viewController.view addConstraint:[NSLayoutConstraint constraintWithItem:textView
//                                                                    attribute:NSLayoutAttributeTop
//                                                                    relatedBy:NSLayoutRelationEqual
//                                                                       toItem:label
//                                                                    attribute:NSLayoutAttributeBottom
//                                                                   multiplier:1
//                                                                     constant:0]];
//    [viewController.view addConstraint:[NSLayoutConstraint constraintWithItem:textView
//                                                                    attribute:NSLayoutAttributeBottom
//                                                                    relatedBy:NSLayoutRelationEqual
//                                                                       toItem:viewController.view
//                                                                    attribute:NSLayoutAttributeBottom
//                                                                   multiplier:1
//                                                                     constant:-5]];
//    [viewController.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[textView]|" options:0 metrics:Nil views:NSDictionaryOfVariableBindings(textView)]];
//    
//    [self.leveyTabBarController.navigationController pushViewController:viewController animated:YES];
//}


#pragma mark 公告公示的评论方式不同，在这里重载父类方法
-(void)commentButtonPress:(commentButton *)button{
    commentView *co=[[commentView alloc]init];
    [co popUpCommentViewWithCommitBlock:^(NSString *commentBody) {
        //设置评论所需的数据并提交评论
        NSMutableDictionary *dic = [[NSMutableDictionary alloc]initWithDictionary:commentWriteRequestData];
        [dic setObject:[NSString stringWithFormat:@"%d",button.theId] forKey:@"gonggaoid"];
        //        PublicityNewsEntity *entity= [PublicMethod entity:kPublicityNewsEntityName WithId:button.theId];
        //        NSLog(@"5");
        //        NSLog(@"entity:%@",entity);
        //        [dic setObject:[entity titleBody] forKey:@"theme"];
        [dic setObject:commentBody forKey:@"content"];
        commentWriteRequestData=[[NSDictionary alloc]initWithDictionary:dic];
        [NetworkCenter AFRequestWithData:commentWriteRequestData SuccessBlock:^(AFHTTPRequestOperation *operation, id resultObject) {
            
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:resultObject options:NSJSONReadingMutableLeaves error:nil];
            if ([dic[@"result"] isEqualToString:@"success"]){
                [Alert showAlert:@"评论成功"];
            } else {
                [Alert showAlert:@"评论失败"];
            }
            [co closeCommentView];
        } FailureBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
        }];
    }];
}

@end
